package com.epam.training;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.epam.training.formvalidate.RegisterForm;
import com.epam.training.repository.CustomerRepository;
import com.epam.training.repository.UserRepository;
import com.epam.training.service.user.UserServiceImpl;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);

	@Autowired
	private UserRepository repository;

	@Autowired
	private CustomerRepository csRepository;

	private String PAGE_ERROR_MESSAGE_ATRIBUE = "errorMessage";
	private String PAGE_MESSAGE_ATRIBUE = "message";

	@Autowired
	private UserServiceImpl userService;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		// logger.info("Welcome home! The client locale is {}.", locale);
		//
		// Date date = new Date();
		// DateFormat dateFormat =
		// DateFormat.getDateTimeInstance(DateFormat.LONG,
		// DateFormat.LONG, locale);
		//
		// String formattedDate = dateFormat.format(date);

		return "home";
	}

	@RequestMapping(value = "/admin")
	public String getAdminPage(Model model) {

		return "admin";
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String homeLogin(Locale locale, Model model) {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String homeLoginReguest(Locale locale, Model model,
			@RequestParam(required = false) String message,
			@RequestParam(required = false) String errorMessage) {
		if (message != null) {
			model.addAttribute(PAGE_MESSAGE_ATRIBUE, message);
		}

		if (errorMessage != null) {
			model.addAttribute("errorMessage", errorMessage);
		}

		return "login";
	}

	@RequestMapping(value = "/error403", method = RequestMethod.GET)
	public String errorPage(Locale locale, Model model) {
		return "error403";
	}

	@RequestMapping(value = "/login/failure", method = RequestMethod.GET)
	public String errorPage(Model model) {
		model.addAttribute(PAGE_ERROR_MESSAGE_ATRIBUE, "login.failure");

		return "redirect:/login";
	}

	@RequestMapping(value = "logout/success", method = RequestMethod.GET)
	public String logoutSuccess() {
		return "redirect:/";
	}

	@RequestMapping(value = "/register")
	public String register(Model model) {
		model.addAttribute("registerForm", new RegisterForm());
		
		return "register";
	}
}
